﻿using System;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;

namespace WikeSoft.Web
{
    /// <summary>
    /// IIdentity扩展
    /// </summary>
    public static class IdentityExtention
    {
        /// <summary>
        /// 获取登录的用户ID
        /// </summary>
        /// <param name="identity">IIdentity</param>
        /// <returns></returns>
        public static string GetLoginUserId(this IIdentity identity)
        {
            var claimIdentity = identity as ClaimsIdentity;
            if (claimIdentity == null) return string.Empty;

            var claim = claimIdentity.FindFirst("LoginUserId");
            return claim != null ? claim.Value : string.Empty;
        }

        /// <summary>
        /// 获取登录用户的PostId
        /// </summary>
        /// <param name="identity">IIdentity</param>
        /// <returns></returns>
        public static Guid GetPostId(this IIdentity identity)
        {
            var claimIdentity = identity as ClaimsIdentity;
            if (claimIdentity == null) return Guid.Empty;

            var claim = claimIdentity.FindFirst("PostId");
            return claim != null ? Guid.Parse(claim.Value) : Guid.Empty;
        }

        /// <summary>
        /// 获取登录用户的真实姓名
        /// </summary>
        /// <param name="identity">IIdentity</param>
        /// <returns></returns>
        public static string GetTrueName(this IIdentity identity)
        {
            var claimIdentity = identity as ClaimsIdentity;
            if (claimIdentity == null) return string.Empty;

            var claim = claimIdentity.FindFirst("TrueName");
            return claim != null ? claim.Value : string.Empty;
        }

        public static Guid[] GetRoles(this IIdentity identity)
        {
            var claimIdentity = identity as ClaimsIdentity;
            return claimIdentity?.Claims.Where(c => c.Type == "RolesGroup").Select(c => new Guid(c.Value)).ToArray();
        }
    }
}